package com.stox.client.embedded.watchlist;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stox.client.api.watchlist.WatchlistClient;
import com.stox.client.api.watchlist.event.WatchlistAddedEvent;
import com.stox.client.api.watchlist.event.WatchlistDeletedEvent;
import com.stox.client.api.watchlist.event.WatchlistEditedEvent;
import com.stox.services.watchlist.manager.WatchlistManager;
import com.stox.shared.event.EventPublisher;
import com.stox.shared.model.Watchlist;

@Component
public class EmbeddedWatchlistClient implements WatchlistClient {

	@Autowired
	private WatchlistManager watchlistManager;
	
	@Override
	public List<Watchlist> findAll() {
		return watchlistManager.findAll();
	}

	@Override
	public Long saveOrUpdate(Watchlist watchlist) {
		boolean isSave = null == watchlist.getId() || 0 == watchlist.getId(); 
		Long id = watchlistManager.saveOrUpdate(watchlist);
		watchlist.setId(id);
		EventPublisher.publishEvent(isSave ? new WatchlistAddedEvent(this, watchlist) : new WatchlistEditedEvent(this, watchlist));
		return id;
	}

	@Override
	public void delete(Long id) {
		watchlistManager.delete(id);
		EventPublisher.publishEvent(new WatchlistDeletedEvent(this, id));
	}

}
